package com.pan.crawler.impl7;

import com.pan.crawler.Directory;
import com.pan.entity.BookDirectory;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 网站 www.beqege.cc
 *
 * 借助搜索引擎进行搜素 site:www.beqege.cc
 */
public class DirectoryImpl7 implements Directory {

    private final String webUrl = "www.beqege.cc";


    public DirectoryImpl7(){

    }

    @Override
    public BookDirectory get(String url) {
        if (url.indexOf(webUrl) == -1){
            throw new RuntimeException("该网站不是："+webUrl);
        }
        BookDirectory bookDirectory = new BookDirectory();
        EdgeDriver edgeDriver = new EdgeDriver();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        edgeDriver.navigate().to(url);
        String bookName = edgeDriver.findElement(By.id("info"))
                .findElement(By.tagName("h1")).getText();
        bookDirectory.setBookName(bookName);
        List<Chapter> chapters = new ArrayList<>();
        WebElement listWebElement = edgeDriver.findElement(By.id("list"));
        int i = 0;
        for (WebElement aElement:listWebElement.findElements(By.tagName("a"))){
            String href = aElement.getAttribute("href");
            String chapterName = aElement.getText();
            chapters.add(new Chapter(i++,chapterName, href));
        }
        bookDirectory.setChapterList(chapters);
        edgeDriver.quit();
        return bookDirectory;
    }
}
